import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { PrimaryC, PrimaryGhostC, TableC } from '../../../../comps';
import { Spin } from 'antd';
import style from './index.less';
import url from '../../../../assets/busi/workStation/Barra/hold_bg.png';
import _ from 'lodash';
import TheTrialC from './theTrialC';
import BookkeepingC from './bookkeepingC';
import accounting from 'accounting';
import CardC from '../../Barra/comps/cardC';

@connect(({ portfolioTrialM, availableAssetM, loading, productManageM }) => ({ portfolioTrialM, availableAssetM, loading, productManageM }))
export default class TradeTrial extends PureComponent {
  static defaultProps = {
    onRef: () => {}, // 本组件的引用
  };

  constructor(props) {
    super(props);
    this.state = {
      showContent: true, // 默认展开
      theTrialIsShow: false, // 试算模态框是否打开
      bookkeepingIsShow: false, // 簿记模态框是否打开
      productCode: '', // 产品code
      dataSource: [], // 表格数据
      expandedRowKeys: [], // 默认展开项
      toneFund: '', // T+1可用
      tzeroFund: '', // T+0可用
      activeIndex: '', // 高亮行
      portfolioId: '', // 组合id，获取可用资金
      productId: '', // 产品id
      isLoading: false, // 获取资金loading
    };
  }

  componentDidMount() {
    // this.props.onRef(this)
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props.productCode != nextProps.productCode) {
      this.setState({ productCode: nextProps.productCode }, () => {
        this.getTableData();
        this.props.securityCodeChange({});
      });
    }
    if (nextProps.state == 2 || nextProps.state == 4 || nextProps.state == 15 || nextProps.state == 16) {
      // 展开
      this.setState({
        showContent: true,
      });
    } else {
      // 收起
      this.setState({
        showContent: false,
      });
    }
  }

  // 获取表格数据
  getTableData = () => {
    const { productCode } = this.state;
    this.props.dispatch({
      type: 'portfolioTrialM/getPortfolioList',
      payload: {
        portfolioCodes: [productCode],
        workStation: true,
      },
      callback: (data) => {
        if (data == 'fail') {
          this.setState({
            dataSource: [],
          });
        } else {
          // 判断是否是持仓（持仓不需要children
          data.dataSource.map((item) => {
            if (item.stockCode) return;
            item.children = [];
          });

          if (data.dataSource && data.dataSource.length == 0) {
            this.setState({
              dataSource: [],
            });
            return;
          }
          this.setState({
            dataSource: data.dataSource,
            portfolioId: data.dataSource[0].portfolioId,
            productId: data.dataSource[0].portfolioId,
          });
          setTimeout(() => {
            // 防止刷新时默认不展开产品节点
            this.setState({
              expandedRowKeys: [data.dataSource[0].id],
            });
          }, 0);
          this.selectPortfolioList(data.dataSource[0]);
          this.getFundsAvailable(data.dataSource[0].portfolioId, data.dataSource[0].portfolioCode);
        }
      },
    });
  };

  // 获取展开表格数据
  selectPortfolioList = (value) => {
    this.props.dispatch({
      type: 'portfolioTrialM/selectPortfolioList',
      payload: {
        portfolioCode: value.portfolioCode,
        totalMarketValue: value.marketValue,
        adjustedTotalMarketValue: value.adjustedMarketValue,
        workStation: true,
      },
      callback: (data) => {
        if (data && data.dataSource.length) {
          // 判断是否是持仓（持仓不需要children
          data.dataSource.map((item) => {
            item.pCode = value.portfolioCode;
            if (item.stockCode) return;
            item.children = [];
          });
          const dataList = this.setDataList(value.id, data.dataSource, this.state.dataSource);

          this.setState({
            dataSource: dataList,
          });
        }
      },
    });
  };

  // 获取可用资金
  getFundsAvailable = (nodeId, portfolioCode) => {
    if (nodeId) {
      this.setState({ isLoading: true });
      let productArg;
      let url = 'availableAssetM/getFund';
      // 交易试算模块根据【交易模式】，调用不同接口获取资金：若是指令/簿记模式，则调用新的资金接口，若不是，则调用老的接口
      if (this.props.modes === 'COMMAND_MODE' || this.props.modes === 'BOOKKEEPING_MODE') {
        productArg = { portfolioCode };
        url = 'availableAssetM/queryAvailable';
      } else {
        productArg = { nodeId };
      }
      this.props.dispatch({
        type: url,
        payload: { ...productArg, hkType: '1' },
        callback: (data) => {
          if (data) {
            if (this.props.modes === 'COMMAND_MODE' || this.props.modes === 'BOOKKEEPING_MODE')
              data = [
                {
                  tzeroAvailableFund: data?.t0Fund,
                  toneAvailableFund: data?.t1Fund,
                },
              ];
          }

          if (data && data.length) {
            const { toneAvailableFund, tzeroAvailableFund } = data[0];
            this.setState({
              toneFund: toneAvailableFund ? accounting.formatNumber(Number(toneAvailableFund), 2) : '',
              tzeroFund: tzeroAvailableFund ? accounting.formatNumber(Number(tzeroAvailableFund), 2) : '',
            });
          } else {
            this.setState({
              toneFund: '',
              tzeroFund: '',
            });
          }
          this.setState({ isLoading: false });
        },
      });
    }
  };

  // 表格行扩展
  onExpandChange = (expanded, record) => {
    if (!expanded || record.children.length > 0) return;
    this.selectPortfolioList(record);
  };

  // 刷新列表
  refresh = () => {
    this.getTableData();
  };

  // 插入children
  setDataList = (id, data, list) => {
    const listItem = [...list];
    let arr = [];
    if (listItem.length > 0) {
      arr = listItem.filter((item) => {
        return item.id == id;
      });
    }
    if (arr.length > 0) {
      listItem.map((item) => {
        if (id == item.id) {
          item.children = data;
        }
      });
    } else {
      listItem.map((item) => {
        if (item.stockCode) return;
        item.children = this.setDataList(id, data, item.children);
      });
    }
    return listItem;
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    columns.forEach((element) => {
      if (element.dataIndex == 'stockCode') {
        // 证券代码样式
        element.render = (text, record) => {
          if (record.assetType) {
            if (record.assetType == '非标') {
              return (
                <a onClick={() => this.stockOnClick(record)}>
                  {' '}
                  {text}--{record.stockName}{' '}
                </a>
              );
            } else if (record.assetType == '现金' || record.assetType == null) {
            } else {
              return (
                <div>
                  {text}--{record.stockName}
                </div>
              );
            }
          }
        };
      }
      if (element.dataIndex == 'amount') {
        element.align = 'right';
        element.render = (text, record) => {
          if (record.assetType == '现金' || record.assetType == null) {
            return;
          }
          const value = parseInt(record.adjustedAmount) - parseInt(record.amount);
          return (
            <span>
              {!text && text != 0 ? '--' : text}
              {(text || text == 0) && value !== 0 ? (
                <span className={value > 0 ? 'plus' : 'reduce'}>
                  {value > 0 ? '+' : '-'}
                  {Math.abs(value)}
                </span>
              ) : null}
            </span>
          );
        };
      }
    });
    return columns;
  };

  // 证券代码点击
  stockOnClick = (record) => {
    if (this.state.portfolioId !== record.portfolioId) {
      this.setState({
        portfolioId: record.portfolioId, // 组合id
      });
      this.getFundsAvailable(record.portfolioId, record.pCode);
    }
    this.setState({
      activeIndex: record.id, // 获取点击行的索引
    });
    this.props.securityCodeChange(record);
  };

  // 响应展开收起
  onExpendClick = (e) => {
    this.setState(
      {
        showContent: e,
      },
      () => {
        this.props.stateOnChange(e ? 1 : 2);
      },
    );
  };

  // 响应试算按钮点击
  theTrial = () => {
    this.setState({ theTrialIsShow: true });
  };

  // 响应簿记按钮点击
  bookkeeping = () => {
    this.setState({ bookkeepingIsShow: true });
  };

  // 模态框取消点击
  onCancel = () => {
    this.setState({ theTrialIsShow: false, bookkeepingIsShow: false });
  };

  // 表格高亮行
  setClassName = (record) => {
    return record.id === this.state.activeIndex ? 'selectRow' : '';
  };

  render() {
    const { showContent, theTrialIsShow, bookkeepingIsShow, dataSource, expandedRowKeys, toneFund, tzeroFund, productCode, productId, isLoading } = this.state;
    const {
      portfolioTrialM: { columns },
      loading,
      state,
      productManageM,
    } = this.props;
    const newColumns = this.changeColumns(columns);
    return (
      <div className={style.mainBox}>
        <div className={style.openBox} style={{ display: showContent ? 'block' : 'none', overflow: 'hidden' }}>
          {/* 展开 */}
          <CardC
            title='交易试算'
            type='12'
            titleTip={
              <Spin spinning={isLoading}>
                <span style={{ marginRight: '16px' }}>T+0可用：{tzeroFund ? `${tzeroFund}元` : '--'} </span>
                <span>T+1可用：{toneFund ? `${toneFund}元` : '--'}</span>
              </Spin>
            }
            showContent={showContent}
            onExpendClick={this.onExpendClick}
            content={
              <div className={style.boxContent}>
                <div className={style.buttonBox}>
                  <PrimaryC title='试算' onClick={this.theTrial} />
                  {['VALUATION_TABLE_ANALYSIS_MODE', 'VALUATION_BOOKKEEPING_MODEL'].includes(productManageM?.currentModes) ? null : (
                    <PrimaryGhostC title='簿记' onClick={this.bookkeeping} />
                  )}

                  <PrimaryGhostC title='刷新' onClick={this.refresh} />
                </div>
                <div className={style.tablec}>
                  <TableC
                    columns={newColumns}
                    dataSource={dataSource}
                    rowKey='id'
                    hidePage={true}
                    scroll={{ x: 1241, y: 385 }}
                    loading={loading.effects['portfolioTrialM/getPortfolioList'] === true || loading.effects['portfolioTrialM/selectPortfolioList'] === true}
                    onExpand={(expanded, record) => this.onExpandChange(expanded, record)} // 点击行展开事件
                    rowClassName={this.setClassName} // 表格行点击高亮
                    expandedRowKeys={expandedRowKeys}
                    onExpandedRowsChange={(expandedRowKeys) => {
                      this.setState({ expandedRowKeys });
                    }}
                  />
                </div>
                {theTrialIsShow && <TheTrialC visible={theTrialIsShow} modes={this.props.modes} onCancel={this.onCancel} productCode={productCode} />}
                {bookkeepingIsShow && <BookkeepingC visible={bookkeepingIsShow} onCancel={this.onCancel} portfolioId={productId} />}
              </div>
            }
          />
        </div>
        <div className={style.closeBox} style={{ display: showContent ? 'none' : 'block', overflow: 'hidden' }}>
          {/* 收起 */}
          <CardC
            title='交易试算'
            type='2'
            titleTip={
              !showContent ? (
                false
              ) : (
                <Spin spinning={isLoading}>
                  <span style={{ marginRight: '16px' }}>T+0可用：{toneFund ? `${toneFund}元` : '--'}</span>
                  <span>T+1可用：{tzeroFund ? `${tzeroFund}元` : '--'}</span>
                </Spin>
              )
            }
            showContent={showContent}
            onExpendClick={this.onExpendClick}
            content={
              <div>
                <div className={style.boxContent}>
                  <div>
                    该产品当前持仓市值为
                    <span>
                      {' '}
                      {dataSource[0]?.adjustedMarketValue || dataSource[0]?.adjustedMarketValue == 0
                        ? accounting.formatNumber(Number(dataSource[0]?.adjustedMarketValue), 2)
                        : '--'}{' '}
                    </span>
                    元
                  </div>
                  <div>
                    收益率为
                    <span>
                      {' '}
                      {dataSource[0]?.adjustedYield || dataSource[0]?.adjustedYield == 0 ? accounting.formatNumber(Number(dataSource[0]?.adjustedYield * 100), 2) : '--'}{' '}
                    </span>
                    %
                  </div>
                </div>

                <div className={style.closeBoxbg}>
                  <img src={url} />
                </div>
              </div>
            }
          />
        </div>
      </div>
    );
  }
}
